
#include <stdio.h>
#include <windows.h>

#define _VER "1.0.0"

void help(HANDLE hStdout)
{
	::SetConsoleTextAttribute(hStdout, FOREGROUND_RED | FOREGROUND_INTENSITY);

	printf("clr - Change the font color in terminal " _VER " ("__DATE__")\n");
	printf("Usage: clr code text\n");
	printf("  code  -  color code from 00 to 0F\n");
	printf("  text  -  the content to display\n");

	printf("\nExamples:\n");
	for (unsigned char c = 1; c <= 0x0f; c++)
	{
		::SetConsoleTextAttribute(hStdout, (WORD)c);
		printf("  Color %02X\n", c);
	}
}

bool getclr(const char *code, WORD *clr)
{
	int len = strlen(code);
	*clr = 0;

	if (len != 2)
		return false;

	for (int i = 0; i < len; i++)
	{
		if (!isxdigit(code[i]))
			return false;

		*clr <<= 4;

		if (isdigit(code[i]))
			*clr += code[i] - '0';
		else
			*clr += toupper(code[i]) - 'A' + 10;
	}

	return true;
}

int main(int argc, char **argv)
{
	HANDLE hStdout = ::GetStdHandle(STD_OUTPUT_HANDLE);
	WORD color = 0;

	CONSOLE_SCREEN_BUFFER_INFO csbi;
	::GetConsoleScreenBufferInfo(hStdout, &csbi);

	if (argc < 2)
	{
		printf("%02X", csbi.wAttributes);
		return 0;
	}

	if (!getclr(argv[1], &color))
	{
		help(hStdout);
		::SetConsoleTextAttribute(hStdout, csbi.wAttributes);
		return 1;
	}

	::SetConsoleTextAttribute(hStdout, (WORD)color);

	if (argc == 2)
	{
		return 0;
	}

	for (int i = 2; i < argc; i++)
	{
		printf("%s ", argv[i]);
	}

	::SetConsoleTextAttribute(hStdout, csbi.wAttributes);

	return 0;
}
